package com.estar.worktime.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import java.io.OutputStream;
import org.jeecgframework.core.util.BrowserUtils;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.util.ResourceUtil;
import java.io.IOException;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.util.Map;
import org.jeecgframework.core.util.ExceptionUtil;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;

import com.estar.app.business.mobileLogin.entity.AppUserEntity;
import com.estar.appuser.service.TmblAppUserServiceI;
import com.estar.workparent.entity.TmblWorktimeParentEntity;
import com.estar.workplace.entity.TmblWorkPlaceEntity;
import com.estar.worktime.entity.TmblWorktimeEntity;
import com.estar.worktime.entity.WorkTableVO;
import com.estar.worktime.service.TmblWorktimeServiceI;

/**   
 * @Title: Controller  
 * @Description: TMBL_WORKTIME
 * @author onlineGenerator
 * @date 2017-04-06 14:33:18
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/tmblWorktimeController")
@Scope("prototype")
public class TmblWorktimeController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(TmblWorktimeController.class);

	@Autowired
	private TmblWorktimeServiceI tmblWorktimeService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	
	@Autowired
	private TmblAppUserServiceI tmblAppUserService;
	
	@Autowired
	private ExcelWorkTableList excelTableList;
	/**
	 * TMBL_WORKTIME列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "lists")
	public ModelAndView list(HttpServletRequest request) {
		request.setAttribute("pid", request.getParameter("pid"));
		return new ModelAndView("gdia/worktime/tmblWorktimeList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(TmblWorktimeEntity tmblWorktime,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TmblWorktimeEntity.class, dataGrid);
		try{
		request.setCharacterEncoding("UTF-8");
		
/*		Date workDate=tmblWorktime.getWorkdate();*/
		
		String pid =request.getParameter("pid");
		TmblWorktimeParentEntity twp=this.systemService.findUniqueByProperty(TmblWorktimeParentEntity.class, "id", pid);
		//获取所有父id
		String sql1="select w.id from tmbl_worktime_parent w where w.DAY='"+twp.getDay()+"'";
		List<String> lis=this.systemService.findListbySql(sql1);
		
		cq.in("parentId", lis.toArray());
		String name=tmblWorktime.getEmpname();
		if(StringUtil.isNotEmpty(name)){
			String name1="%"+name+"%";
			cq.like("empname", name1);
			tmblWorktime.setEmpname("");
		}
		
		String beginDate = request.getParameter("workdate_begin");
		String endDate = request.getParameter("workdate_end");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		if(StringUtil.isNotEmpty(beginDate)){
			cq.add(Restrictions.ge("workdate", sdf.parse(beginDate)));
		}
		if(StringUtil.isNotEmpty(endDate)){
			cq.add(Restrictions.le( "workdate",sdf.parse(endDate)));
		}
		
		
		/*if(workDate!=null){
			cq.eq("workdate", workDate);
		}*/
		cq.addOrder("empcdoe", SortDirection.desc);
		cq.addOrder("workdate", SortDirection.asc);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tmblWorktime, request.getParameterMap());
		
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.tmblWorktimeService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除TMBL_WORKTIME
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(TmblWorktimeEntity tmblWorktime, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		j.setSuccess(true);
		tmblWorktime = systemService.getEntity(TmblWorktimeEntity.class, tmblWorktime.getId());
		message = "TMBL_WORKTIME删除成功";
		try{
			tmblWorktimeService.delete(tmblWorktime);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "TMBL_WORKTIME删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除TMBL_WORKTIME
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		String message = null;
		AjaxJson j = new AjaxJson();
		j.setSuccess(true);
		message = "TMBL_WORKTIME删除成功";
		try{
			for(String id:ids.split(",")){
				TmblWorktimeEntity tmblWorktime = systemService.getEntity(TmblWorktimeEntity.class, 
				id
				);
				tmblWorktimeService.delete(tmblWorktime);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "TMBL_WORKTIME删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加TMBL_WORKTIME
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(TmblWorktimeEntity tmblWorktime, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "排班总览表添加成功";
		try{
			tmblWorktimeService.save(tmblWorktime);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "排班总览表添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新TMBL_WORKTIME
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(TmblWorktimeEntity tmblWorktime, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "排班总览表更新成功";
		TmblWorktimeEntity t = tmblWorktimeService.get(TmblWorktimeEntity.class, tmblWorktime.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(tmblWorktime, t);
			tmblWorktimeService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "排班总览表更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	

	/**
	 * TMBL_WORKTIME新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(TmblWorktimeEntity tmblWorktime, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tmblWorktime.getId())) {
			tmblWorktime = tmblWorktimeService.getEntity(TmblWorktimeEntity.class, tmblWorktime.getId());
			req.setAttribute("tmblWorktimePage", tmblWorktime);
		}
		return new ModelAndView("gdia/worktime/tmblWorktime-add");
	}
	/**
	 * TMBL_WORKTIME编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(TmblWorktimeEntity tmblWorktime, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tmblWorktime.getId())) {
			tmblWorktime = tmblWorktimeService.getEntity(TmblWorktimeEntity.class, tmblWorktime.getId());
			req.setAttribute("tmblWorktimePage", tmblWorktime);
		}
		return new ModelAndView("gdia/worktime/tmblWorktime-update");
	}
	
	
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public void exportXls(TmblWorktimeEntity tmblWorktime,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		try{
			String name =request.getParameter("name");
			//System.out.println("======"+name);
			CriteriaQuery cq = new CriteriaQuery(TmblWorktimeEntity.class, dataGrid);
			String pid =request.getParameter("pid");
			TmblWorktimeParentEntity twp=this.systemService.findUniqueByProperty(TmblWorktimeParentEntity.class, "id", pid);
			//获取所有父id
			String sql1="select w.id from tmbl_worktime_parent w where w.DAY='"+twp.getDay()+"'";
			List<String> lis=this.systemService.findListbySql(sql1);
			cq.in("parentId", lis.toArray());
			if(StringUtil.isNotEmpty(name)){
				String str = new String(name.getBytes("ISO8859-1"), "UTF-8"); 
				cq.like("empname", "%"+name+"%");
				//System.out.println("======"+str);
				tmblWorktime.setEmpname("");
			}
			
			String beginDate = request.getParameter("begin");
			String endDate = request.getParameter("end");
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			if(StringUtil.isNotEmpty(beginDate)){
				cq.add(Restrictions.ge("workdate", sdf.parse(beginDate)));
			}
			if(StringUtil.isNotEmpty(endDate)){
				cq.add(Restrictions.le( "workdate",sdf.parse(endDate)));
			}
			
			Map<String, String[]> m=request.getParameterMap();
			cq.addOrder("empcdoe", SortDirection.desc);
			cq.addOrder("workdate", SortDirection.asc);
			org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tmblWorktime, request.getParameterMap());
			
			//cq.add();
			
			List<TmblWorktimeEntity> tmblWorktimes = this.tmblWorktimeService.getListByCriteriaQuery(cq,false);
			TmblWorktimeParentEntity wp=this.systemService.get(TmblWorktimeParentEntity.class, pid);
			this.excelTableList.excelTable(wp.getDay()+"的明细表", request, response, tmblWorktimes);
		}catch(Exception e){
			logger.error("导出明细表系统错误",e);
		}
	}
	
	@RequestMapping(params = "doSaveTable")
	@ResponseBody
	@Transactional
	public String daSaveTable(WorkTableVO workTableVO, HttpServletRequest req) {
		String message = null;
		//AjaxJson j = new AjaxJson();
		message = "保存排班表成功！请关闭页面";
		
		try{
			TSUser u = ResourceUtil.getSessionUserName();
			List<TmblWorktimeEntity> wtList=workTableVO.getWtList();
			for(TmblWorktimeEntity wt:wtList){
				wt.setCreateName(u.getUserName());
				wt.setCreateDate(new Date());
				this.tmblWorktimeService.save(wt);
			}
		}catch(Exception e){
			message = "保存排班表失败！";
			logger.error("保存排班表系统异常："+e);
		}
		//j.setMsg(message);
		boolean flag=true;
		String json="{\"msg\":\""+message+"\",\"success\":"+flag+"}";
		return json;
	}
	
	@RequestMapping(params = "doUpdateTable")
	@ResponseBody
	@Transactional
	public String doUpdateTable(WorkTableVO workTableVO, HttpServletRequest req) {
		String message = null;
		//AjaxJson j = new AjaxJson();
		//j.setSuccess(true);
		boolean flag=true;
		message = "保存排班表成功！请关闭页面，如若修改，关闭当前页面重新进入";
		try{
			TSUser u = ResourceUtil.getSessionUserName();
			List<TmblWorktimeEntity> wtList=workTableVO.getWtList();
			for(TmblWorktimeEntity wt:wtList){
				TmblWorktimeEntity newWt=systemService.get(TmblWorktimeEntity.class, wt.getId());
				if(StringUtil.isEmpty(newWt.getWork())){//存在记录的就不需要修改
					newWt.setWorkplace(wt.getWorkplace());
					newWt.setWorkPlaceId(wt.getWorkPlaceId());
					newWt.setParentId(wt.getParentId());
					newWt.setWorkdate(wt.getWorkdate());
					newWt.setEmpcdoe(wt.getEmpcdoe());
					newWt.setEmpname(wt.getEmpname());
					newWt.setUpdateName(u.getUserName());
					newWt.setUpdateDate(new Date());
					this.tmblWorktimeService.updateEntitie(newWt);
				}
			}
			List<TmblWorktimeEntity> addwtList=workTableVO.getAddWtList();
			if(addwtList!=null && addwtList.size()>0){
			for(TmblWorktimeEntity wt:addwtList){
				if(StringUtil.isNotEmpty(wt.getEmpname())){
					if (StringUtil.isNotEmpty(wt.getId())) {
						TmblWorktimeEntity newWt=systemService.get(TmblWorktimeEntity.class, wt.getId());						
						if(StringUtil.isEmpty(newWt.getWork())){
							newWt.setWorkplace(wt.getWorkplace());
							newWt.setWorkPlaceId(wt.getWorkPlaceId());
							newWt.setParentId(wt.getParentId());
							newWt.setWorkdate(wt.getWorkdate());
							newWt.setEmpcdoe(wt.getEmpcdoe());
							newWt.setEmpname(wt.getEmpname());
							newWt.setUpdateName(u.getUserName());
							newWt.setUpdateDate(new Date());
							newWt.setState("2");
							this.tmblWorktimeService.updateEntitie(newWt);
						}
					}else{
						TmblWorktimeEntity newWt=new TmblWorktimeEntity();
						newWt.setWorkplace(wt.getWorkplace());
						newWt.setWorkPlaceId(wt.getWorkPlaceId());
						newWt.setParentId(wt.getParentId());
						newWt.setWorkdate(wt.getWorkdate());
						newWt.setEmpcdoe(wt.getEmpcdoe());
						newWt.setEmpname(wt.getEmpname());
						newWt.setCreateName(u.getUserName());
						newWt.setCreateDate(new Date());
						newWt.setState("2");
						this.tmblWorktimeService.save(newWt);
					}
					
				}
			}
			}
		}catch(Exception e){
			flag=false;
			message = "保存排班表失败！";
			logger.error("保存排班表系统异常："+e);
			e.printStackTrace();
		}
		//j.setMsg(message);
		String json="{\"msg\":\""+message+"\",\"success\":"+flag+"}";
		return json;
	}
			//Spring接受前台的数据超过256
			//这个类初始化的时候会首先调用init方法
		   @InitBinder  //类初始化是调用的方法注解
		    public void initBinder(WebDataBinder binder) {  
		        //给这个controller配置接收list的长度100000，仅在这个controller有效
		        binder.setAutoGrowCollectionLimit(2000); 

		    }
		
		   
		   
		   
		 
		
				
				
}
